package com.etoak.config;

import com.etoak.filter.CrossFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Value("${image.path}")
    String pathPrefix;

    @Value("${image.dir}")
    String uploadDir;
    /**
     * 配置跨域过滤器
     */
    @Bean
    public FilterRegistrationBean<CrossFilter> crossFilter(){
        FilterRegistrationBean<CrossFilter> registrationBean = new FilterRegistrationBean<>();
        //filter-class
        registrationBean.setFilter(new CrossFilter());
        //url-pattern
        registrationBean.addUrlPatterns("/*");
        registrationBean.setOrder(1);
        return registrationBean;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        //  /files/**
        String mapping = pathPrefix.endsWith("/") ?
                StringUtils.join(pathPrefix,"**") :
                StringUtils.join(pathPrefix,"/**");

        // location = file:d:/upload/et2108/
        String location = uploadDir.endsWith("/") ?
                StringUtils.join("file:",uploadDir) :
                StringUtils.join("file:",uploadDir,"/");
        registry.addResourceHandler(mapping).addResourceLocations(location);
    }
}
